package org.example.daojishi;

//import org.apache.commons.lang3.time.DateFormatUtils;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 时间工具类
 *
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }
    /**
     * 计算相差分钟
     */
    public static int differentMinutesByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 60)));
    }

    /**
     * 计算相差几秒钟
     *
     * @param time1
     * @param time2
     * @return
     */
    public static int differentSecondByTimestamp(Long time1, Long time2) {
        return Math.abs((int) ((time2 - time1) / (1000)));
    }

    public static int differentSecondByTime(Long time1, Long time2) {
        return Math.round((int) ((time2 - time1) / (1000)));
    }
    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 时间大小比较 time_2 >= time_1 返回true
     *
     * @param time_1
     * @param time_2
     * @return
     */
    public static boolean compareTime(String time_1, String time_2) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
            Date current = simpleDateFormat.parse(time_1);
            Date compare = simpleDateFormat.parse(time_2);

            long number = compare.getTime() - current.getTime();

            if (number >  0) {
                return true;
            } else {
                return false;
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 时间转换
     *
     * @param oldWord  格式化时间
     * @param newWord  需要交换时间
     * @param dateTime 时间字符串
     * @return
     */
    public static Date formatTime(String oldWord, String newWord, String dateTime) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        try {
            String exchangeDate = dateTime.replace(oldWord, newWord);
            return simpleDateFormat.parse(exchangeDate);
        } catch (Exception e) {
            return null;
        }
    }


    public static Date stringToDate(String dateTime, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取两个日期相隔日期
     *
     * @return
     */
    public static List<String> getDayList(Date date, Integer day) {
        List<String> result = new ArrayList<String>();
        Calendar cal = Calendar.getInstance();
        for (int i = 1; i <= day; i++) {
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_MONTH, -(day - i));
            result.add(parseDateToStr(YYYY_MM_DD, cal.getTime()));
        }
        return result;
    }



    /**
     * 获取当前日期时分秒毫秒
     *
     * @return
     */
//    public static String getHmsS() {
//        String hmsS = DateUtil.format(new Date(), "HHmmssSSS");
//        return hmsS;
//    }

    /**
     * 获取当前日期时间分秒毫秒(避免同时播放ssrc重复)
     * 最大支持1000路同时api访问，后期需要优化
     * @return
     */
//    public static synchronized String getHmsSsynchronized() {
//        String hmsS = DateUtil.format(new Date(), "HHmmssSSS");
//        try {
//            Thread.sleep(1);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        return hmsS;
//
//    }
    /**
     * 获取时间格式
     * @param date
     * @return
     */
//    public static String formaterDate2(Date date) {
//        String result = DateUtil.format(date,"HHmmssSSS");
//        return result;
//    }

    /**
     * 获取前几分钟的时间
     *
     * @return
     */
    public static String getMinuteAgoTime(int minuteInt) {
        String minute = "";
        Date date = new Date();//获取当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minuteInt);// 30分钟前
        //获取到完整的时间
        minute = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        return minute;
    }

    public static String getDateString(Date date) {
        SimpleDateFormat formater = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return formater.format(date);
    }

    /**
     * long类型转string
     *
     * @param dateLong
     * @return
     */
    public static String longToString(long dateLong) {
        Date date = new Date(dateLong);
        return getDateString(date);
    }

    /**
     * 根据{days}分割时间段
     *
     * @return map key: startTime value: endTime
     */
    public static Map<Date, Date> dateSplitByDay(Date startDate, Date endDate, int days) {
        Map<Date, Date> dateMap = new TreeMap<>();
        long l = endDate.getTime() - startDate.getTime();
        long intervalMills = days * 24 * 3600 * 1000L;
        if (l > intervalMills) {
            long segment = l / intervalMills;
            boolean left = l % intervalMills != 0;

            Date temp = startDate;
            for (int j = 0; j < segment; j++) {
                Date next = DateUtils.addDays(temp, days);
                dateMap.put(temp, next);
                temp = next;

                if (j == segment - 1 && left) {
                    dateMap.put(next, endDate);
                }
            }
        } else {
            dateMap.put(startDate, endDate);
        }

        return dateMap;
    }

    /**
     * 上面的重载方法
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @param days  分割天数
     * @return
     * @throws ParseException
     */
    public static Map<Date, Date> dateSplitByDay(String startDate, String endDate, int days) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return dateSplitByDay(sdf.parse(startDate), sdf.parse(endDate), days);
    }

    /**
     * {minites}分钟分割时间段，返回分割的段数
     *
     * @param startDate
     * @param endDate
     * @param minutes
     * @return
     */
    public static long getSegmentLengthSplitByMinutes(Date startDate, Date endDate, int minutes) {
        long left = (endDate.getTime() - startDate.getTime())  / 60000; // 转分钟
        return left % minutes == 0 ? left / minutes : left / minutes + 1;
    }

    public static long getSegmentLengthSplitByMinutes(String startDate, String endDate, int minutes) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
        return getSegmentLengthSplitByMinutes(sdf.parse(startDate), sdf.parse(endDate), minutes);
    }


    public static long getSecondsDifference(Date date1, Date date2) {
        long diffInMilliseconds = date2.getTime() - date1.getTime();
        return TimeUnit.MILLISECONDS.toSeconds(diffInMilliseconds);
    }
}
